{% extends "base.html" %}

{% block title %}管理员首页 - 学生管理系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-tachometer-alt me-2"></i>管理员工作台</h2>
    <div>
        <a href="{{ url_for('statistics') }}" class="btn btn-outline-info">
            <i class="fas fa-chart-bar me-1"></i>详细统计
        </a>
    </div>
</div>

<!-- 统计信息卡片 -->
<div class="row mb-4">
    <!-- 学生统计 -->
    <div class="col-md-4 mb-3">
        <div class="card h-100">
            <div class="card-header bg-primary text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-users me-2"></i>学生信息
                </h5>
            </div>
            <div class="card-body">
                <div class="text-center mb-3">
                    <i class="fas fa-user-graduate fa-3x text-primary"></i>
                </div>
                <h3 class="text-center" id="totalStudents">加载中...</h3>
                <p class="text-center text-muted">学生总数</p>
                
                <div class="mt-3">
                    <small class="text-muted">年级分布：</small>
                    <div id="gradeDistribution" class="mt-1">
                        <div class="text-center text-muted">
                            <i class="fas fa-spinner fa-spin"></i> 加载中...
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-3">
                    <a href="{{ url_for('index') }}" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-list me-1"></i>查看所有学生
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 课程统计 -->
    <div class="col-md-4 mb-3">
        <div class="card h-100">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-book me-2"></i>课程信息
                </h5>
            </div>
            <div class="card-body">
                <div class="text-center mb-3">
                    <i class="fas fa-book-open fa-3x text-success"></i>
                </div>
                <h3 class="text-center" id="totalCourses">加载中...</h3>
                <p class="text-center text-muted">课程总数</p>
                
                <div class="mt-3">
                    <small class="text-muted">总学分：</small>
                    <div class="fw-bold" id="totalCredits">加载中...</div>
                </div>
                
                <div class="mt-2">
                    <small class="text-muted">教师数量：</small>
                    <div class="fw-bold" id="totalTeachers">加载中...</div>
                </div>
                
                <div class="text-center mt-3">
                    <a href="{{ url_for('courses') }}" class="btn btn-sm btn-outline-success">
                        <i class="fas fa-cog me-1"></i>课程管理
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 选课统计 -->
    <div class="col-md-4 mb-3">
        <div class="card h-100">
            <div class="card-header bg-info text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-tasks me-2"></i>选课情况
                </h5>
            </div>
            <div class="card-body">
                <div class="text-center mb-3">
                    <i class="fas fa-clipboard-list fa-3x text-info"></i>
                </div>
                <h3 class="text-center" id="totalSelections">加载中...</h3>
                <p class="text-center text-muted">总选课人次</p>
                
                <div class="mt-3">
                    <small class="text-muted">平均选课：</small>
                    <div class="fw-bold" id="avgCourses">加载中...</div>
                </div>
                
                <div class="mt-2">
                    <small class="text-muted">参与率：</small>
                    <div class="fw-bold" id="participationRate">加载中...</div>
                </div>
                
                <div class="text-center mt-3">
                    <a href="{{ url_for('selection') }}" class="btn btn-sm btn-outline-info">
                        <i class="fas fa-eye me-1"></i>查看选课
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 热门课程排行 -->
<div class="row">
    <div class="col-md-6 mb-4">
        <div class="card h-100">
            <div class="card-header bg-warning text-dark">
                <h5 class="card-title mb-0">
                    <i class="fas fa-fire me-2"></i>热门课程排行
                </h5>
            </div>
            <div class="card-body">
                <div id="popularCourses">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                        <p>加载热门课程...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 选课分布 -->
    <div class="col-md-6 mb-4">
        <div class="card h-100">
            <div class="card-header bg-secondary text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-chart-pie me-2"></i>选课分布
                </h5>
            </div>
            <div class="card-body">
                <div id="courseDistribution">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                        <p>加载选课分布...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 快速操作 -->
<div class="card mt-4">
    <div class="card-header bg-light">
        <h5 class="card-title mb-0">
            <i class="fas fa-bolt me-2"></i>快速操作
        </h5>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3 col-6 mb-2">
                <a href="{{ url_for('add_student') }}" class="btn btn-outline-primary w-100">
                    <i class="fas fa-user-plus me-1"></i>添加学生
                </a>
            </div>
            <div class="col-md-3 col-6 mb-2">
                <a href="{{ url_for('courses') }}" class="btn btn-outline-success w-100">
                    <i class="fas fa-plus-circle me-1"></i>添加课程
                </a>
            </div>
            <div class="col-md-3 col-6 mb-2">
                <a href="{{ url_for('import_students') }}" class="btn btn-outline-info w-100">
                    <i class="fas fa-file-import me-1"></i>导入数据
                </a>
            </div>
            <div class="col-md-3 col-6 mb-2">
                <a href="/export/excel" class="btn btn-outline-secondary w-100">
                    <i class="fas fa-download me-1"></i>导出数据
                </a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 页面加载时获取统计数据
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardStats();
});

// 加载仪表板统计数据
async function loadDashboardStats() {
    try {
        const response = await fetch('/api/stats');
        if (!response.ok) {
            throw new Error('获取统计数据失败');
        }
        const stats = await response.json();
        renderDashboardStats(stats);
    } catch (error) {
        console.error('加载统计数据失败:', error);
        // 显示错误信息
        document.querySelectorAll('.card-body').forEach(card => {
            if (card.innerHTML.includes('加载中')) {
                card.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        加载失败: ${error.message}
                    </div>
                `;
            }
        });
    }
}

// 渲染仪表板统计数据
function renderDashboardStats(stats) {
    // 学生统计
    document.getElementById('totalStudents').textContent = stats.total || 0;
    
    // 年级分布
    const gradeDistribution = document.getElementById('gradeDistribution');
    if (stats.grade && stats.grade.length > 0) {
        gradeDistribution.innerHTML = stats.grade.map(grade => `
            <span class="badge bg-light text-dark me-1 mb-1">
                ${grade._id}: ${grade.count}
            </span>
        `).join('');
    } else {
        gradeDistribution.innerHTML = '<span class="text-muted">无数据</span>';
    }
    
    // 课程统计
    document.getElementById('totalCourses').textContent = stats.course_stats?.total_courses || 0;
    document.getElementById('totalCredits').textContent = '计算中...';
    document.getElementById('totalTeachers').textContent = '计算中...';
    
    // 选课统计
    document.getElementById('totalSelections').textContent = stats.course_stats?.total_enrollment || 0;
    document.getElementById('avgCourses').textContent = stats.student_course_stats?.avg_courses_per_student || 0;
    document.getElementById('participationRate').textContent = 
        stats.student_course_stats?.participation_rate ? 
        stats.student_course_stats.participation_rate + '%' : '0%';
    
    // 热门课程
    renderPopularCourses(stats.course_stats?.popular_courses || []);
    
    // 选课分布
    renderCourseDistribution(stats.student_course_stats?.distribution || []);
    
    // 计算总学分和教师数量
    calculateCourseStats(stats.course_stats?.course_enrollment || []);
}

// 渲染热门课程
function renderPopularCourses(courses) {
    const popularCoursesDiv = document.getElementById('popularCourses');
    
    if (courses.length === 0) {
        popularCoursesDiv.innerHTML = `
            <div class="text-center text-muted py-3">
                <i class="fas fa-graduation-cap fa-2x mb-2"></i>
                <p>暂无选课数据</p>
            </div>
        `;
        return;
    }
    
    popularCoursesDiv.innerHTML = courses.map((course, index) => `
        <div class="d-flex justify-content-between align-items-center mb-2 p-2 border-bottom">
            <div>
                <span class="badge bg-warning me-2">${index + 1}</span>
                <span class="fw-bold">${course.course_name}</span>
                <br>
                <small class="text-muted">${course.enrolled}/${course.capacity}人</small>
            </div>
            <span class="badge bg-success">${course.enrollment_rate}%</span>
        </div>
    `).join('');
}

// 渲染选课分布
function renderCourseDistribution(distribution) {
    const distributionDiv = document.getElementById('courseDistribution');
    
    if (distribution.length === 0) {
        distributionDiv.innerHTML = `
            <div class="text-center text-muted py-3">
                <i class="fas fa-chart-pie fa-2x mb-2"></i>
                <p>暂无选课分布数据</p>
            </div>
        `;
        return;
    }
    
    distributionDiv.innerHTML = distribution.map(item => `
        <div class="d-flex justify-content-between align-items-center mb-2 p-2 border-bottom">
            <span>${item.courses}门课程</span>
            <span class="badge bg-secondary">${item.students}人</span>
        </div>
    `).join('');
}

// 计算课程统计信息
function calculateCourseStats(courses) {
    let totalCredits = 0;
    const teachers = new Set();
    
    courses.forEach(course => {
        totalCredits += course.credits || 0;
        if (course.teacher) {
            teachers.add(course.teacher);
        }
    });
    
    document.getElementById('totalCredits').textContent = totalCredits + ' 学分';
    document.getElementById('totalTeachers').textContent = teachers.size + ' 位';
}
</script>
{% endblock %}
